package code.c11;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/11/17 11:15
 * @package code.c11
 * @description 文件说明
 */

public class MyJFrame4 extends JFrame {
    JTextField jTextField;
    JButton button_1;

    public MyJFrame4(String title) throws HeadlessException {
        super.setTitle(title);
        this.init();
    }

    public void init() {
        super.setSize(485, 300);
        super.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        super.setLayout(new FlowLayout());

        button_1 = new JButton("button_1");
        jTextField = new JTextField(10);

        // 定义一个事件监听器
        MyActionListener myActionListener = new MyActionListener();
        button_1.addActionListener(myActionListener);

        myActionListener.setjTextField(jTextField);

        super.add(button_1);
        super.add(jTextField);
        super.setVisible(true);
    }

    public static void main(String[] args) {
        new MyJFrame4("aaa");
    }
}

class MyActionListener implements ActionListener{

    JTextField jTextField = new JTextField(10);

    public void setjTextField(JTextField jTextField) {
        this.jTextField = jTextField;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            // 读取文本框中的数字
            int num = Integer.parseInt(jTextField.getText());
            System.out.println(num);
            // 将数字平方后输入到文本框中
            jTextField.setText(String.valueOf(Math.pow(num,2)));
            System.out.println(num * num);
        } catch (NumberFormatException numberFormatException) {
            numberFormatException.printStackTrace();
            jTextField.setText("数据转换失败，请重新输入正确的数字");
        }
    }
}
